<?php

namespace App\Http\Controllers\V1\Upload;

use App\Models\V1\Department;
use Illuminate\Http\Request;
use App\Http\Requests\V1\ImportDataRequest;
use Maatwebsite\Excel\Facades\Excel;
use App\Events\V1\ImportExportEvent;
use Jenssegers\Agent\Agent;
use Illuminate\Support\Facades\Auth;

class DepartmentExcelUploadController extends BaseExcelUploadController
{
    /**
     * 导入部门数据
     *
     * @param Request $request
     */
    public function importData(ImportDataRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '部门数据导入失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateImport($request);

            $filePath = $request->input('successFile');
            $fileExtension = $request->input('extension');

            Excel::load($filePath, function($reader) use ($fileExtension) {
                $reader->limitColumns(6);
                //忽略空的cells
                $reader->ignoreEmpty();
                $data = $reader->toArray();
                collect($data) -> flatMap(function($item) use ($fileExtension) {
                    $insert_data = [
                        'code' => $item[0],
                        'name' => $item[1],
                        'telephone' => isset($item[2])?$item[2]:'',
                        'parent_code' => isset($item[3])?$item[3]: '0',
                        'show_level' => isset($item[4])?$item[4]: 0,
                        'principal' => isset($item[5])?$item[5]:''
                    ];
                    if (!empty($item[0]) && !empty($item[1])) {
                        Department::updateOrCreate(['code'=>$item[0]],$insert_data);
                    }
                });
            });

            $response['rspStatus'] = true;
            $response['rspMsg'] = [
                'type' => 'import',
                'msg' => '成功导入['.$request->input('successFile').']文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $request->getClientIp(), time(), $response['rspMsg']));

            return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
        }
    }

    /**
     * 导出部门数据文件
     *
     * @param Request $request
     */
    public function exportData(Request $request)
    {
        $clientIP = $request->getClientIp();

        $header = ['部门代码', '部门名称', '办公电话电话', '所属部门代码', '优先级','负责人'];
        $custodian = Department::all(['code', 'name', 'telephone', 'parent_code', 'show_level','principal']);
        $cellDatas = [$header];
        foreach ($custodian as $item) {
            $cellData = [
                $item->code,
                $item->name,
                $item->telephone,
                $item->parent_code,
                $item->show_level,
                $item->principal
            ];
            array_push($cellDatas, $cellData);
        }

        Excel::create(iconv('UTF-8', 'GBK','校内部门'), function ($excel) use ($cellDatas, $clientIP) {
            $excel->sheet('department', function ($sheet) use ($cellDatas) {
                $sheet->rows($cellDatas);
            });

            $response['rspMsg'] = [
                'type' => 'export',
                'msg' => '成功下载[校内部门]导出文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $clientIP, time(), $response['rspMsg']));
        })->export('xls');
    }
}
